package com.sdy.hospitalguard.biz.utils;


import com.sdy.common.utils.EncodeUtil;
import com.sdy.common.utils.RandomUtil;

import java.util.Random;

/**
 * @author: 王越洋
 * @version: v1.0
 * @description: com.sdy.hospitalguard.biz.utils
 * @date:2020/6/1
 */
public class PassWordUtil {

    /**
     * 注册时加密密码
     *
     * @param sha256 前端传入加密后密码
     * @return
     */
    public static String registerEncryption(String sha256) {
        String randomNickname = RandomUtil.produceStringAndNumber(6);

        String pwdOne = EncodeUtil.sha256(sha256 + randomNickname) + "#" + randomNickname;
        return pwdOne;
    }

    /**
     * 登录时效验密码
     *
     * @param sha256 前端传入加密后密码
     * @param dbPwd  数据库查出的密码
     * @return
     */
    public static Boolean loginVerify(String sha256, String dbPwd) {
        String salt = dbPwd.split("#")[1];
        String pwd = dbPwd.split("#")[0];
        String pwdOne = EncodeUtil.sha256(sha256 + salt);
        if (pwd.equals(pwdOne)) {
            return true;
        }
        return false;
    }


    /**
     * 生成 salt
     *
     * @return
     */
    private static String getRandomNickname() {
        String val = "";
        Integer length = 6;
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            if ("char".equalsIgnoreCase(charOrNum)) {
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (choice + random.nextInt(26));
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }
}
